//
//  ZYLoginViewController.swift
//  WeiBoAPP
//
//  Created by ios001 on 2022/3/8.
//  Copyright © 2022 zxf. All rights reserved.
//

import UIKit

class ZYLoginViewController: ZFBaseViewController, UITextFieldDelegate {

    var phoneTF:UITextField?
    var pwdTF:UITextField?
    var loginSuccess:kLoginSuccessBlock?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "登录";
        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
// MARK: UI
extension ZYLoginViewController{
    
    override func setupUI() {
        super.setupUI()
        let textFieldView = setupTextFeildUI(topView: nil);
        setupLoginButtonUI(topView: textFieldView)
    }
    override func setupTableView() {
        
    }
    
    override func setupNavUI() {
        super.setupNavUI()
        navItem.rightBarButtonItem = UIBarButtonItem(title: "注册", target: self, action: #selector(registAction),isBack:false)

        
    }
    // 点击注册
    @objc func registAction() {
        
        let registerVC = ZYRegisterViewController.init()
        registerVC.registerBlock = { [weak self] in
            print("注册完成回调，请重新登录")
            
            self?.phoneTF?.text = "123"
        }
        self.navigationController?.pushViewController(registerVC, animated: true)
    }
    
    
    // 创建UI
    func setupTextFeildUI(topView:UIView?) -> UIView {
        
        var lastBgView:UIView = UIView.init()
        for i  in 0..<2 {
            let bgView = UIView.init()
            bgView.backgroundColor = UIColor.white
//            bgView.layer.borderColor = UIColor.red.cgColor
//            bgView.layer.borderWidth = 1
            view.addSubview(bgView)
            
            bgView.snp.makeConstraints { make in
                make.height.equalTo(50)
                make.left.right.equalToSuperview()
                if i == 0 {
//                    make.top.equalTo(box1.snp.top).offset(20) //top等于box1.top，再向下偏离20
                    make.top.equalTo(kNavigationHeight)
                }else{
//                    make.top.equalTo(0)
                    make.top.equalTo(lastBgView.snp.bottom)
                }
            }
        
            lastBgView = bgView;
            
            // 标题
            let label = UILabel.init()
            label.font = UIFont.systemFont(ofSize: 15)
            label.textColor = UIColor.black
            label.text = "标题"
            bgView.addSubview(label)
            // 输入框
            let textField = UITextField.init()
            textField.placeholder = "请输入...";
            textField.font  = UIFont.systemFont(ofSize: 14)
            textField.borderStyle = UITextField.BorderStyle.roundedRect
            textField.delegate = self
            bgView.addSubview(textField)
            if i == 0 {
                phoneTF = textField
                label.text = "用户名"
                textField.placeholder = "请输入用户名4位";
                textField.returnKeyType = UIReturnKeyType.done
                textField.text = "1234"
            }else{
                pwdTF = textField
                label.text = "密码"
                textField.placeholder = "请输入至少6位密码";
                textField.keyboardType = UIKeyboardType.numberPad
            }

            
            label.snp.makeConstraints { make in
                make.left.equalTo(15)
                make.centerY.equalToSuperview()
                make.width.equalTo(90)
                make.height.equalTo(20)
            }
            
            textField.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.height.equalTo(35)
                make.left.equalTo(label.snp.right).offset(10)
                make.right.equalTo(bgView.snp.right).offset(-15);
            }
            
        }
   
        // 返回最下一个view
        return lastBgView
    }

    
    // 创建UI
    func setupLoginButtonUI(topView:UIView?)  {
        let bgView = UIView.init()
        bgView.backgroundColor = UIColor.white
        view.addSubview(bgView)
//        bgView.layer.borderColor = UIColor.red.cgColor
//        bgView.layer.borderWidth = 1
        
        bgView.snp.makeConstraints { make in
            make.left.right.centerY.equalToSuperview()
            make.height.equalTo(50)
        }
        
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        button.setTitle("登录", for: UIControl.State.normal)
        button.setTitleColor(UIColor.blue, for: UIControl.State.normal)
        button.layer.borderWidth = 0.5
        button.layer.borderColor = UIColor.blue.cgColor
        button.layer.cornerRadius = 5
        button.addTarget(self, action: #selector(loginButtonAction), for: UIControl.Event.touchUpInside)
        bgView.addSubview(button)
        button.snp.makeConstraints { make in
            make.width.equalTo(180)
            make.height.equalTo(40)
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        

        
    }
    
    // 登录点击事件
    @objc func loginButtonAction (){
        
        view.endEditing(true)
        print("登录")
        if phoneTF?.text?.count ?? 0 <= 0 {
            showAlert(titleStr: "温馨提示", message: "请输入用户名")
            return
        }
        if phoneTF?.text?.count ?? 0 < 4{
            showAlert(titleStr: "温馨提示", message: "用户名长度不小于4位")
            return
        }
        if pwdTF?.text?.count ?? 0 <= 0 {
            showAlert(titleStr: "温馨提示", message: "请输入密码")
            return
        }
        if pwdTF?.text?.count ?? 0 < 6 {
            showAlert(titleStr: "温馨提示", message: "请输入长度大于6位密码")
            return
        }
        print("成功")
        // 延迟5s
        showHuWaiting(title: nil, msg: "正在登录....")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
            self.showHuDing(title: nil, msg: "登录成功")
            
            var info: [String: Any] = [:]
            info["userName"] = self.phoneTF?.text
            info["pwd"] = self.pwdTF?.text

            print(Thread.isMainThread)
            self.navigationController?.popViewController(animated: true)
            
            UserDataConfig.shared.saveUserInfo(info:info)
            UserDataConfig.shared.isLogin = true

            // 注册成功回调
            self.loginSuccess?()
            
        }
    }
    
}




// MARK: delegate
extension ZYLoginViewController {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        
        print(textField.text as Any)
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let limitation = 19
        
        let currentLength = textField.text?.count ?? 0 // 当前长度
        if (range.length + range.location > currentLength){
            return false
        }
        // 禁用启用按钮
        let newLength = currentLength + string.count - range.length // 加上输入的字符之后的长度
        if newLength >= limitation {
            //                    confirmButton.isEnable = true
        } else {
            //                    confirmButton.isEnable = false
        }
        return newLength <= limitation
    }



    
}
